<template>
  <div>
    <el-dialog
      top="5vh"
      width="55%"
      title="查看详情"
      append-to-body
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="dialog-content">
        <avue-form ref="editForm" v-model="form" :option="option">
          <template slot="code">
            <el-input placeholder="请输入编码" v-model="form.code" disabled>
              <el-button slot="append" size="small" icon="el-icon-refresh-right"></el-button>
            </el-input>
          </template>
          <template slot="preview">
            <el-input v-model="preview" disabled> </el-input>
          </template>
          <template slot="standerCode">
            <h3>标准代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" disabled>
                <div v-for="(item, index) in seqNoRulesList">
                  <el-col :span="8" class="col">
                    <el-checkbox disabled :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="pubulicCode">
            <h3>公用代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" disabled>
                <div v-for="(item, index) in publicRuleList">
                  <el-col :span="6" class="col">
                    <el-checkbox :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="otherCode">
            <h3>类型代码</h3>
            <div class="seqNoRulesList">
              <el-checkbox-group v-model="selectedCode" disabled>
                <div v-for="(item, index) in otherRuleList">
                  <el-col :span="6" class="col">
                    <el-checkbox :key="item.key" class="custom-check-box" :label="item.key">{{ item.value }}</el-checkbox>
                  </el-col>
                </div>
              </el-checkbox-group>
            </div>
          </template>
          <template slot="customCode">
            <h3>自定义字符</h3>
            <div class="data-source">
              <label>数据源:</label>
              <el-tooltip class="item" effect="dark" :content="form.sqlName" placement="top">
                <el-input placeholder="请选择 数据源" v-model="form.sqlName" disabled>
                  <el-button slot="append" icon="el-icon-search"></el-button>
                </el-input>
              </el-tooltip>
            </div>
            <el-checkbox-group v-model="selectedCode" disabled>
              <div v-for="(item, index) in customizedPlaceholder">
                <el-col :span="8">
                  <el-checkbox :key="item.code" class="custom-check-box" :label="item.code">{{ item.label + item.code }}</el-checkbox>
                  <el-button type="text" size="small" icon="el-icon-view" @click="handleEditSubForm(item, index)">查看 </el-button>
                </el-col>
              </div>
            </el-checkbox-group>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      top="5vh"
      width="30%"
      title="自定义字符详情"
      append-to-body
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="subVisible"
      @close="handleSudEditReset"
    >
      <avue-form ref="subForm" v-model="subForm" :option="subOption" @submit="handleSubmitCustom"> </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-delete" @click="handleSudEditReset">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOtherCode, getPublicCode, getStranderCode, getKeyValueMap } from '@/util/global';
import { getDetail, getSqlName } from '@/api/admin/sequencedefinition';

export default {
  name: 'viewSerialNumber',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      customKey: [],
      fieldMap: getKeyValueMap(),
      subForm: {},
      subOption: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        span: 24,
        column: [
          {
            label: '字符名称',
            prop: 'label',
            disabled: true
          },
          {
            label: '字符代码',
            prop: 'code',
            disabled: true
          },
          {
            label: '默认值',
            prop: 'value',
            disabled: true
          }
        ]
      },
      seqNoRulesList: getStranderCode(),
      publicRuleList: getPublicCode(),
      otherRuleList: [],
      customRuleList: [],
      customizedPlaceholder: [],
      selectedCode: [],
      subVisible: false,
      subTitle: '',
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        column: [
          {
            label: '大类',
            prop: 'type',
            type: 'select',
            disabled: true,
            span: 8,
            cascader: ['subType'],
            dicUrl: '/api/blade-system/dict/dictionary?code=serial',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择大类',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '小类',
            prop: 'subType',
            disabled: true,
            dicUrl: '/api/blade-system/dict/dictionary?code={{key}}',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            type: 'select',
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择小类',
                trigger: 'blur'
              }
            ],
            change: ({ column, value }) => {
              if (value) {
                this.otherRuleList = getOtherCode(value);
              } else {
                this.otherRuleList = [];
              }
            }
          },
          {
            label: '规则名称',
            prop: 'name',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入规则名称',
                trigger: 'blur'
              }
            ],
            span: 8
          },
          {
            label: '序列号ID',
            prop: 'code',
            disabled: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入序列号ID',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '进制类型',
            prop: 'hexType',
            disabled: true,
            span: 8,
            labelTip: '序列号生成流水的进制，十进制为10进1，十六进制为16进1；如进制类型为十进制，</br> 则进制字符为0123456789',
            type: 'select',
            rules: [
              {
                required: true,
                message: '请输入进制类型',
                trigger: 'blur'
              }
            ],
            dicData: [
              {
                label: '十进制',
                value: '10'
              },
              {
                label: '十六进制',
                value: '16'
              },
              {
                label: '自定义',
                value: 'custom'
              }
            ],
            control: (val, form) => {
              if (val === 'custom') {
                return {
                  hexString: {
                    disabled: true
                  }
                };
              } else {
                return {
                  hexString: {
                    disabled: true
                  }
                };
              }
            },
            change: (val) => {
              if (val.value === '10') {
                this.form.hexString = '0123456789';
              } else if (val.value === '16') {
                this.form.hexString = '0123456789ABCDEF';
              }
            }
          },
          {
            label: '进制字符',
            prop: 'hexString',
            disabled: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入进制字符',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '起始流水号',
            prop: 'startSequenceNo',
            disabled: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入起始流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '结束流水号',
            prop: 'endSequenceNo',
            disabled: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请输入结束流水号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '清零类型',
            prop: 'regressionType',
            disabled: true,
            type: 'select',
            dicData: [
              {
                label: '不清零',
                value: ''
              },
              {
                label: '年',
                value: 'Year'
              },
              {
                label: '月',
                value: 'Month'
              },
              {
                label: '周',
                value: 'Week'
              },
              {
                label: '日',
                value: 'Day'
              }
            ],
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择清零类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '前缀字符',
            prop: 'prefix',
            disabled: true,
            span: 8
          },
          {
            label: '后缀字符',
            prop: 'suffix',
            disabled: true,
            span: 8
          },
          {
            label: '分隔符',
            disabled: true,
            span: 8,
            prop: 'delimiter',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=delimiter_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '增量',
            prop: 'incrementQty',
            disabled: true,
            type: 'number',
            span: 8
          },
          {
            label: '预生成序列号',
            prop: 'isPregenerated',
            type: 'switch', //开关的类型
            align: 'center',
            value: false,
            disabled: true
          },
          {
            label: '序列号构成规则',
            disabled: true,
            prop: 'sequenceNoFormat',
            span: 24,
            rules: [
              {
                required: true,
                message: '请选择序列号构成规则',
                trigger: 'change'
              }
            ]
          },
          {
            label: '序列号规则预览',
            prop: 'preview',
            slot: true,
            span: 24
          },
          {
            label: '',
            prop: 'standerCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'pubulicCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'otherCode',
            formslot: true,
            labelWidth: 40,
            span: 24
          },
          {
            label: '',
            prop: 'customCode',
            labelWidth: 40,
            formslot: true,
            span: 24
          }
        ]
      }
    };
  },
  computed: {
    preview() {
      let str = '';
      this.selectedCode.forEach((item) => {
        if (this.customKey.includes(item)) {
          str += this.customizedPlaceholder.find((el) => el.code === item).value || '';
        } else if (this.form.prefix && item === '[P]') {
          // 前缀 和后缀 字符 有值时取其值  无值去默认值
          str += this.form.prefix;
        } else if (this.form.suffix && item === '[B]') {
          str += this.form.suffix;
        } else {
          str += this.fieldMap[item] || '';
        }
      });
      return str;
    }
  },
  methods: {
    async getRowData(id) {
      try {
        const res = await getDetail(id);
        const data = res.data.data;
        if (data.placeholderDataId) {
          const sqlRes = await getSqlName(data.placeholderDataId);
          const sqlData = sqlRes.data.data || {};
          data.sqlName = sqlData.querySql;
        }
        this.formatField(data);
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.$refs.editForm.resetForm();
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    handleSudEditReset() {
      this.$refs.subForm.resetForm();
      this.subVisible = false;
    },
    handleSubEditSubmit() {
      this.$refs.subForm.submit();
    },
    handleSubmitCustom(form, done) {
      if (this.editIndex === -1) {
        this.customRuleList.push(form);
      } else {
        this.customRuleList.splice(this.editIndex, 1, form);
      }
      done();
      this.subVisible = false;
      this.$refs.subForm.resetForm();
    },
    async handleEditSubmit(form, done) {
      console.log(this.selectedRuleCodes);
      // try {
      //   const res = await updateTable(data);
      //   console.log(res);
      // } catch (e) {
      //   console.warn(e);
      // }
      done();
      this.showEditDialog = false;
      this.$emit('closeDialog');
    },

    handleEditSubForm(item, index) {
      this.subVisible = true;
      this.subForm = item;
      this.subTitle = '详情';
      this.editIndex = index;
    },
    formatField(data) {
      const form = data;
      let reg = /^[0-9]\d*$/g;
      let str = /^[A-F0-9]+$/;
      // 回显进制
      if (!form.hexType) {
        // 兼容问题历史数据  之前没有这个字段 现在有了. 对于之前数据走这个逻辑
        if (reg.test(form.hexString)) {
          form.hexType = '10';
        } else if (str.test(form.hexString)) {
          form.hexType = '16';
        } else {
          form.hexType = 'custom';
        }
      }

      // 回显checkBox
      const regex = /\[[^\]]+\]/g;
      const matches = form.sequenceNoFormat.match(regex);
      this.selectedCode = matches;
      // 回显自定义
      if (form.customizedPlaceholder) {
        this.customizedPlaceholder = JSON.parse(form.customizedPlaceholder);
        this.customKey = this.customizedPlaceholder.map((item) => item.code);
      } else {
        this.customizedPlaceholder = [];
      }
      this.form = form;
      console.log(this.form);
    }
  }
};
</script>

<style scoped lang="scss">
h3 {
  margin: 0;
  line-height: 30px;
}
.add-custom-btn {
  font-size: 14px;
}
.dialog-content {
  height: 70vh;
  overflow-y: scroll;
}
.col {
  line-height: 30px;
  .custom-check-box {
    display: flex;
    align-items: center;
    line-height: 30px;
  }
}

.data-source {
  display: flex;
  margin: 12px 0;
  label {
    width: 60px;
  }
}
</style>
